import axios from "axios";

// 创建 axios 实例
const api = axios.create({
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});
// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response?.status === 401) {
      // 清除本地存储的 token
      localStorage.removeItem("token");
      // 跳转到登录页
      // window.location.href = "/login";
    }
    return Promise.reject(error);
  }
);

// 认证相关 API
export const authAPI = {
  login: (username: string, password: string) =>
    api.post("/api/auth/login", { username, password }),

  register: (username: string, password: string, email?: string) =>
    api.post("/api/auth/register", { username, password, email }),

  logout: () => api.post("/api/auth/logout"),

  getProfile: () => api.get("/api/auth/profile"),
};

// 聊天室相关 API
export const chatroomAPI = {
  // 获取我的聊天室
  getMyRooms: () => api.get("/api/chatrooms/my"),

  // 搜索聊天室
  searchRooms: (keyword: string) =>
    api.get("/api/chatrooms/search", { params: { keyword } }),

  // 获取聊天室详情
  getRoom: (roomId: string) => api.get(`/api/chatrooms/${roomId}`),

  // 创建聊天室
  createRoom: (data: {
    name: string;
    description?: string;
    isPublic?: boolean;
    isSearchable?: boolean;
    password?: string;
    maxUsers?: number;
  }) => api.post("/api/chatrooms", data),

  // 更新聊天室
  updateRoom: (roomId: string, data: any) =>
    api.put(`/api/chatrooms/${roomId}`, data),

  // 加入聊天室
  joinRoom: (roomId: string, password?: string) =>
    api.post(`/api/chatrooms/${roomId}/join`, { password }),

  // 离开聊天室
  leaveRoom: (roomId: string) => api.post(`/api/chatrooms/${roomId}/leave`),

  // 删除聊天室
  deleteRoom: (roomId: string) => api.delete(`/api/chatrooms/${roomId}`),
};

// 消息相关 API
export const messageAPI = {
  // 获取聊天室消息
  getMessages: (roomId: string, page = 1, limit = 50) =>
    api.get(`/api/chat/${roomId}/messages`, {
      params: { page, limit },
    }),

  // 发送消息
  sendMessage: (roomId: string, content: string, type = "text") =>
    api.post(`/api/chat/${roomId}/messages`, { content, type }),

  // 删除消息
  deleteMessage: (messageId: string) =>
    api.delete(`/api/messages/${messageId}`),
};

// 用户相关 API
export const userAPI = {
  // 获取用户信息
  getUser: (userId: string) => api.get(`/api/users/${userId}`),

  // 更新用户信息
  updateUser: (data: any) => api.put("/api/users/profile", data),

  // 获取在线用户
  getOnlineUsers: (roomId: string) => api.get(`/api/chatrooms/${roomId}/users`),
};

// 文件上传相关 API
export const uploadAPI = {
  // 上传文件
  uploadFile: (file: File) => {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("fileName", file.name);
    return api.post("/api/upload", formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
      timeout: 30000, // 30秒超时，文件上传可能需要更长时间
    });
  },

  // 获取文件
  getFile: (fileId: string) => api.get(`/api/upload/${fileId}`),

  // 删除文件
  deleteFile: (fileId: string) => api.delete(`/api/upload/${fileId}`),
};

// 获取文件URL
export function getFileUrl(filePath: string) {
  if (!filePath) return "";

  // 如果已经是完整URL，直接返回
  if (filePath.startsWith("http")) {
    return filePath;
  }

  // 如果路径以/uploads开头，通过API访问文件
  if (filePath.startsWith("/uploads/")) {
    // 从路径中提取文件名
    const fileName = filePath.split("/").pop();
    // 通过API访问文件，这样可以避免CORS问题
    return `/api/upload/file/${fileName}`;
  }

  // 其他情况拼接API基础URL
  return `/api${filePath}`;
}

export default api;
